package com.xlx.gateway.filter;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import com.xlx.common.utils.JsonResult;
import com.xlx.common.utils.UsersLoginKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author xlx
 */
@Slf4j
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String name = Thread.currentThread().getName();
        log.info("name:{}",name);

        //带了login的请求直接放行
        if (request.getURI().getPath().contains("/login")||request.getURI().getPath().contains("/msg")) {
            log.info("请求带了login直接放行");
            return chain.filter(exchange);
        }

        HttpHeaders headers = request.getHeaders();
        // String token = headers.getFirst("X-Token");
        String token = headers.getFirst("Authorization");
        log.info("获取到的token:{}",token);
        //不带请求头的请求直接放行
        if (token==null||token.isBlank()) {
            log.info("请求不带token直接放行");
            return chain.filter(exchange);
        }
        //校验token
        String key = UsersLoginKey.USERS_KET;
        boolean validate = JWT.of(token).setKey(key.getBytes()).validate(0);
        //合法的token直接放行
        if (validate) {
            log.info("token合法，放行");
            return chain.filter(exchange);
        }
        log.info("token不合法，不放行");
        //返回自定义的json
        byte[] bytes = JSONUtil.toJsonStr(JsonResult.error("token不合法")).getBytes(StandardCharsets.UTF_8);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
